/**
 * Filename: BrowseActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/13 16:24
 */
package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.MachineListAdapter;
import com.github.postsanf.yinian.adapter.ViewPagerAdapter;
import com.github.postsanf.yinian.bean.ShowPicWallTime;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.bean.YNPhoto;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 浏览大图
 */
public class TimeMachineActivity extends BaseActivity {
    //    private RecyclerViewPager mRecyclerView;                              // 整个切换视图
    private int position;                               // 位置
    private MachineListAdapter mAdapter;                               // 适配器
    private List<String> picUrlsList;                            // 图片数据
    private List<String> picThumb;                            // 图片数据
    private YNStatus mDatas;                                 // 该动态数据
    private boolean isFromWall = false;
    private List<YNNativeImage> photosTime = new ArrayList<>();
    private List<YNPhoto> photos = new ArrayList<>();
    private boolean timeWall;
    private ViewPager viewpager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_machine);
//        initData();
        initView();
//        setData();
        showTimePhoto("initialize", null, "day", true);
    }

    private void initData() {
        position = getIntent().getIntExtra(CommonConstants.YNPOSITION, 0);
        isFromWall = getIntent().getBooleanExtra(CommonConstants.YNDATAS, false);
        timeWall = getIntent().getBooleanExtra(CommonConstants.TIMEWALL, false);
        if (isFromWall) {
            photos = (List<YNPhoto>) getIntent().getSerializableExtra(CommonConstants.YNQNURL);
        }
//        if (timeWall) {
//            photosTime = (List<YNNativeImage>) getIntent().getSerializableExtra(CommonConstants.YNQNURL);
//        }
        mDatas = YNSingleton.getInstance().getCurStatus();
        picUrlsList = mDatas.getUrl();
        picThumb = mDatas.getThumbnail();
    }

    private ViewPagerAdapter pagerAdapter;

    private void initView() {
//        mRecyclerView = (RecyclerViewPager) findViewById(R.id.vp_browse);
//        LinearLayoutManager layout = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
//        mRecyclerView.setLayoutManager(layout);
        viewpager = (ViewPager) findViewById(R.id.viewpager);
        pagerAdapter = new ViewPagerAdapter(TimeMachineActivity.this, photosTime);
        viewpager.setAdapter(pagerAdapter);
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                CurrentPageIndex = position;
                loadNextPage();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private int CurrentPageIndex = 0;//当前页面下标

    private void loadNextPage() {
        if (CurrentPageIndex == photosTime.size() - 1) {
            showTimePhoto("loading", dateMore, "day", false);
        }
    }

    private void setData() {
        List<String> urls = new ArrayList<>();
        if (isFromWall) {
            for (int i = 0; i < photos.size(); i++) {
                urls.add(photos.get(i).getUrl());
            }
            mAdapter = new MachineListAdapter(TimeMachineActivity.this, urls);
        } else if (timeWall) {
            for (int i = 0; i < photosTime.size(); i++) {
                urls.add(photosTime.get(i).getPath());
            }
            mAdapter = new MachineListAdapter(TimeMachineActivity.this, urls);
        } else {
            mAdapter = new MachineListAdapter(TimeMachineActivity.this, picUrlsList);
        }
//        mRecyclerView.setAdapter(mAdapter);
//        mRecyclerView.setAdapter(new LayoutAdapter(this, mRecyclerView, urls));
//        mRecyclerView.setHasFixedSize(true);
//        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int scrollState) {
////                updateState(scrollState);
//            }
//
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int i, int i2) {
////                mPositionText.setText("First: " + mRecyclerViewPager.getFirstVisiblePosition());
//                int childCount = mRecyclerView.getChildCount();
//                int width = mRecyclerView.getChildAt(0).getWidth();
//                int padding = (mRecyclerView.getWidth() - width) / 2;
////                mCountText.setText("Count: " + childCount);
//                for (int j = 0; j < childCount; j++) {
//                    View v = recyclerView.getChildAt(j);
//                    //往左 从 padding 到 -(v.getWidth()-padding) 的过程中，由大到小
//                    float rate = 0;
//                    if (v.getLeft() <= padding) {
//                        if (v.getLeft() >= padding - v.getWidth()) {
//                            rate = (padding - v.getLeft()) * 1f / v.getWidth();
//                        } else {
//                            rate = 1;
//                        }
//                        v.setScaleY(1 - rate * 0.1f);
//                        v.setScaleX(1 - rate * 0.1f);
//
//                    } else {
//                        //往右 从 padding 到 recyclerView.getWidth()-padding 的过程中，由大到小
//                        if (v.getLeft() <= recyclerView.getWidth() - padding) {
//                            rate = (recyclerView.getWidth() - padding - v.getLeft()) * 1f / v.getWidth();
//                        }
//                        v.setScaleY(0.9f + rate * 0.1f);
//                        v.setScaleX(0.9f + rate * 0.1f);
//                    }
//                }
//            }
//        });
//        mRecyclerView.addOnPageChangedListener(new RecyclerViewPager.OnPageChangedListener() {
//            @Override
//            public void OnPageChanged(int oldPosition, int newPosition) {
//                Log.d("test", "oldPosition:" + oldPosition + " newPosition:" + newPosition);
//            }
//        });
//        mRecyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
//            @Override
//            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//                if (mRecyclerView.getChildCount() < 3) {
//                    if (mRecyclerView.getChildAt(1) != null) {
//                        if (mRecyclerView.getCurrentPosition() == 0) {
//                            View v1 = mRecyclerView.getChildAt(1);
//                            v1.setScaleY(0.9f);
//                            v1.setScaleX(0.9f);
//                        } else {
//                            View v1 = mRecyclerView.getChildAt(0);
//                            v1.setScaleY(0.9f);
//                            v1.setScaleX(0.9f);
//                        }
//                    }
//                } else {
//                    if (mRecyclerView.getChildAt(0) != null) {
//                        View v0 = mRecyclerView.getChildAt(0);
//                        v0.setScaleY(0.9f);
//                        v0.setScaleX(0.9f);
//                    }
//                    if (mRecyclerView.getChildAt(2) != null) {
//                        View v2 = mRecyclerView.getChildAt(2);
//                        v2.setScaleY(0.9f);
//                        v2.setScaleX(0.9f);
//                    }
//                }
//            }
//        });
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    pagerAdapter.notifyDataSetChanged();
                    mProgressDialog.dismiss();
                    break;
            }
        }
    };
    private ProgressDialog mProgressDialog;

    public void showTimePhoto(final String type, String date, String mode, final boolean dayTime) {
        mProgressDialog = ProgressDialog.show(TimeMachineActivity.this, "", "");
        String urlsto = getString(R.string.BASE_URL) + getString(R.string.ynShowPhotoWallByDayOrMonth);
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, application.getCurGid() + "");
        if (date != null) {
            mParam.put(CommonConstants.DATE, date);
        }
        mParam.put(CommonConstants.YNS_PIC_MODE, mode);
        mParam.put(CommonConstants.YNS_TYPE, type);
        mParam.put(CommonConstants.YNS_CHANELSOURCE, "app");
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        ShowPicWallTime showPicWallTime = gson.fromJson(s, ShowPicWallTime.class);
                        if (TextUtils.equals(showPicWallTime.getMsg(), "success")) {
                            List<ShowPicWallTime.DataBean> data = showPicWallTime.getData();
                            for (int i = 0; i < data.size(); i++) {
                                String upLoadDate = data.get(i).getEuploadtime();
                                List<ShowPicWallTime.DataBean.PictureBean> pictureList = data.get(i).getPicture();
                                for (int j = 0; j < pictureList.size(); j++) {
                                    String thumbnail = pictureList.get(j).getThumbnail();
                                    String path = pictureList.get(j).getUrl();
                                    YNNativeImage mNativeItem = new YNNativeImage();
                                    mNativeItem.setPath(path);
                                    mNativeItem.setTime(upLoadDate);
                                    mNativeItem.setThumbnail(thumbnail);
                                    photosTime.add(mNativeItem);
                                }
                                if (i == data.size() - 1) {
                                    dateMore = data.get(i).getEuploadtime();
                                }
                            }
                            mHandler.sendEmptyMessage(1);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private String dateMore;

}
